<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { formSchema } from './dept.data';
import { useMessage } from '@/hooks/web/useMessage';
import { getOrgList } from '@/api/sys/system';
import { add, edit } from '@/api/sys/restManager';
import { useI18n } from '@/hooks/web/useI18n';

export default defineComponent({
  name: 'DeptModal',
  components: { BasicModal, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const { t } = useI18n();

    let isUpdate = ref(true);
    const { createMessage } = useMessage();
    const [
      registerForm,
      { resetFields, setFieldsValue, updateSchema, validate },
    ] = useForm({
      labelWidth: 100,
      schemas: formSchema,
      baseColProps: { span: 24 },
      showActionButtonGroup: false,
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(
      async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

        if (data.parent) {
          // 部门下只能添加部门
          if (data.parent.orgType === 'depart') {
            setFieldsValue({
              orgType: 'depart',
            });
            updateSchema({
              field: 'orgType',
              componentProps: {
                disabled: true,
              },
            });
          } else {
            updateSchema({
              field: 'orgType',
              componentProps: {
                disabled: false,
              },
            });
          }
          setFieldsValue({
            pid: data.parent.id,
          });
        }

        const treeData = await getOrgList({ hasDepart: true });
        updateSchema({
          field: 'pid',
          label: '上级组织',
          component: 'TreeSelect',
          // 不递归！
          replaceSchema: true,
          required: true,
          componentProps: ({ formModel }) => {
            return {
              fieldNames: {
                label: 'name',
                key: 'id',
                value: 'id',
              },
              getPopupContainer: () => document.body,
              treeData: [
                {
                  id: '0',
                  pid: '-1',
                  name: t('根组织'),
                  children: treeData,
                },
              ],
              onChange: (value: any, selecedName, treeNode) => {
                const dataNode = treeNode.triggerNode.props;
                if (dataNode.orgType === 'depart') {
                  formModel.orgType = 'depart';
                  updateSchema({
                    field: 'orgType',
                    componentProps: {
                      disabled: true,
                    },
                  });
                } else {
                  updateSchema({
                    field: 'orgType',
                    componentProps: {
                      disabled: false,
                    },
                  });
                }
              },
            };
          },
        });
      },
    );

    const getTitle = computed(() =>
      !unref(isUpdate) ? t('新增组织') : t('编辑组织'),
    );

    async function handleSubmit() {
      try {
        const values = await validate();
        setModalProps({ confirmLoading: true });
        // TODO custom api
        if (unref(isUpdate)) {
          await edit('sysOrg', values);
          createMessage.success(t('修改成功'));
        } else {
          await add('sysOrg', values);
          createMessage.success(t('保存成功'));
        }
        closeModal();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return { registerModal, registerForm, getTitle, handleSubmit };
  },
});
</script>
